#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
数据库文件处理模块

提供对SQLite、Access等文件型数据库的读取、写入、查询等功能
"""

import os
import re
import tempfile
from pathlib import Path
from typing import Union, List, Dict, Any, Optional, Tuple, Iterator, Set

# 导入异常处理装饰器
from ..exception.exception_handler import exception_handler
from ..exception.exceptions import FileException, DatabaseException

# 导入日志模块
from ..logger.logger import Logger

# 创建日志记录器
logger = Logger("db_handler").get_logger()


class SQLiteHandler:
    """
    SQLite数据库文件处理类
    
    提供对SQLite数据库文件的读取、写入、查询等功能
    """
    
    def __init__(self):
        """
        初始化SQLite处理器
        """
        try:
            import sqlite3
            self.sqlite3 = sqlite3
        except ImportError as e:
            logger.error(f"初始化SQLite处理器失败: {e}")
            logger.error("sqlite3模块是Python标准库的一部分，请确保Python安装正确")
            raise ImportError("sqlite3模块是Python标准库的一部分，请确保Python安装正确") from e
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def connect(self, db_path: Union[str, Path]) -> 'sqlite3.Connection':
        """
        连接到SQLite数据库
        
        Args:
            db_path: 数据库文件路径
            
        Returns:
            数据库连接对象
            
        Raises:
            DatabaseException: 连接失败时抛出
            
        Examples:
            >>> handler = SQLiteHandler()
            >>> conn = handler.connect('example.db')
            >>> # 使用完毕后关闭连接
            >>> conn.close()
        """
        db_path = Path(db_path)
        
        # 确保数据库目录存在
        db_path.parent.mkdir(parents=True, exist_ok=True)
        
        try:
            # 连接到数据库
            conn = self.sqlite3.connect(str(db_path))
            
            # 启用外键约束
            conn.execute("PRAGMA foreign_keys = ON")
            
            # 设置行工厂，使查询结果可以通过列名访问
            conn.row_factory = self.sqlite3.Row
            
            logger.info(f"连接到SQLite数据库成功: {db_path}")
            return conn
        except Exception as e:
            raise DatabaseException(f"连接到SQLite数据库失败: {e}")
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def execute_query(self, conn: 'sqlite3.Connection', query: str, params: Optional[Tuple] = None) -> List[Dict[str, Any]]:
        """
        执行查询语句
        
        Args:
            conn: 数据库连接对象
            query: SQL查询语句
            params: 查询参数，默认为None
            
        Returns:
            查询结果列表，每个元素是一个字典
            
        Raises:
            DatabaseException: 查询失败时抛出
            
        Examples:
            >>> handler = SQLiteHandler()
            >>> conn = handler.connect('example.db')
            >>> # 执行简单查询
            >>> results = handler.execute_query(conn, "SELECT * FROM users")
            >>> # 执行带参数的查询
            >>> results = handler.execute_query(conn, "SELECT * FROM users WHERE age > ?", (18,))
            >>> conn.close()
        """
        try:
            cursor = conn.cursor()
            
            # 执行查询
            if params:
                cursor.execute(query, params)
            else:
                cursor.execute(query)
            
            # 获取结果
            results = [dict(row) for row in cursor.fetchall()]
            
            cursor.close()
            
            logger.info(f"执行查询成功: {query[:50]}{'...' if len(query) > 50 else ''}")
            return results
        except Exception as e:
            raise DatabaseException(f"执行查询失败: {e}")
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def execute_update(self, conn: 'sqlite3.Connection', query: str, params: Optional[Tuple] = None) -> int:
        """
        执行更新语句（INSERT, UPDATE, DELETE等）
        
        Args:
            conn: 数据库连接对象
            query: SQL更新语句
            params: 更新参数，默认为None
            
        Returns:
            受影响的行数
            
        Raises:
            DatabaseException: 更新失败时抛出
            
        Examples:
            >>> handler = SQLiteHandler()
            >>> conn = handler.connect('example.db')
            >>> # 插入数据
            >>> affected = handler.execute_update(conn, "INSERT INTO users (name, age) VALUES (?, ?)", ("张三", 25))
            >>> # 更新数据
            >>> affected = handler.execute_update(conn, "UPDATE users SET age = ? WHERE name = ?", (26, "张三"))
            >>> # 删除数据
            >>> affected = handler.execute_update(conn, "DELETE FROM users WHERE name = ?", ("张三",))
            >>> conn.commit()  # 提交事务
            >>> conn.close()
        """
        try:
            cursor = conn.cursor()
            
            # 执行更新
            if params:
                cursor.execute(query, params)
            else:
                cursor.execute(query)
            
            # 获取受影响的行数
            affected_rows = cursor.rowcount
            
            cursor.close()
            
            logger.info(f"执行更新成功: {query[:50]}{'...' if len(query) > 50 else ''} (影响 {affected_rows} 行)")
            return affected_rows
        except Exception as e:
            raise DatabaseException(f"执行更新失败: {e}")
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def execute_script(self, conn: 'sqlite3.Connection', script: str) -> None:
        """
        执行SQL脚本
        
        Args:
            conn: 数据库连接对象
            script: SQL脚本内容
            
        Raises:
            DatabaseException: 执行失败时抛出
            
        Examples:
            >>> handler = SQLiteHandler()
            >>> conn = handler.connect('example.db')
            >>> # 执行创建表的脚本
            >>> script = '''
            ... CREATE TABLE IF NOT EXISTS users (
            ...     id INTEGER PRIMARY KEY AUTOINCREMENT,
            ...     name TEXT NOT NULL,
            ...     age INTEGER
            ... );
            ... CREATE INDEX IF NOT EXISTS idx_name ON users(name);
            ... '''
            >>> handler.execute_script(conn, script)
            >>> conn.commit()  # 提交事务
            >>> conn.close()
        """
        try:
            # 执行脚本
            conn.executescript(script)
            
            logger.info(f"执行SQL脚本成功: {script[:50]}{'...' if len(script) > 50 else ''}")
        except Exception as e:
            raise DatabaseException(f"执行SQL脚本失败: {e}")
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def get_tables(self, conn: 'sqlite3.Connection') -> List[str]:
        """
        获取数据库中的所有表名
        
        Args:
            conn: 数据库连接对象
            
        Returns:
            表名列表
            
        Raises:
            DatabaseException: 获取失败时抛出
            
        Examples:
            >>> handler = SQLiteHandler()
            >>> conn = handler.connect('example.db')
            >>> tables = handler.get_tables(conn)
            >>> print(tables)
            >>> conn.close()
        """
        try:
            cursor = conn.cursor()
            
            # 查询所有表
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
            tables = [row['name'] for row in cursor.fetchall()]
            
            cursor.close()
            
            logger.info(f"获取表名列表成功: {', '.join(tables)}")
            return tables
        except Exception as e:
            raise DatabaseException(f"获取表名列表失败: {e}")
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def get_table_schema(self, conn: 'sqlite3.Connection', table_name: str) -> List[Dict[str, Any]]:
        """
        获取表结构信息
        
        Args:
            conn: 数据库连接对象
            table_name: 表名
            
        Returns:
            表结构信息列表，每个元素是一个字段的信息字典
            
        Raises:
            DatabaseException: 获取失败时抛出
            
        Examples:
            >>> handler = SQLiteHandler()
            >>> conn = handler.connect('example.db')
            >>> schema = handler.get_table_schema(conn, 'users')
            >>> for column in schema:
            ...     print(f"字段名: {column['name']}, 类型: {column['type']}")
            >>> conn.close()
        """
        try:
            cursor = conn.cursor()
            
            # 查询表结构
            cursor.execute(f"PRAGMA table_info({table_name})")
            columns = [dict(row) for row in cursor.fetchall()]
            
            cursor.close()
            
            logger.info(f"获取表结构成功: {table_name}")
            return columns
        except Exception as e:
            raise DatabaseException(f"获取表结构失败: {e}")
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def export_to_csv(self, conn: 'sqlite3.Connection', table_name: str, csv_path: Union[str, Path]) -> None:
        """
        将表数据导出为CSV文件
        
        Args:
            conn: 数据库连接对象
            table_name: 表名
            csv_path: CSV文件路径
            
        Raises:
            DatabaseException: 导出失败时抛出
            
        Examples:
            >>> handler = SQLiteHandler()
            >>> conn = handler.connect('example.db')
            >>> handler.export_to_csv(conn, 'users', 'users.csv')
            >>> conn.close()
        """
        csv_path = Path(csv_path)
        
        # 确保输出目录存在
        csv_path.parent.mkdir(parents=True, exist_ok=True)
        
        try:
            import csv
            
            # 获取表结构
            schema = self.get_table_schema(conn, table_name)
            column_names = [col['name'] for col in schema]
            
            # 查询所有数据
            cursor = conn.cursor()
            cursor.execute(f"SELECT * FROM {table_name}")
            rows = cursor.fetchall()
            
            # 写入CSV文件
            with open(csv_path, 'w', newline='', encoding='utf-8') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow(column_names)  # 写入表头
                for row in rows:
                    writer.writerow([row[col] for col in column_names])  # 写入数据行
            
            cursor.close()
            
            logger.info(f"导出表数据到CSV成功: {table_name} -> {csv_path}")
        except Exception as e:
            raise DatabaseException(f"导出表数据到CSV失败: {e}")
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def import_from_csv(self, conn: 'sqlite3.Connection', table_name: str, csv_path: Union[str, Path], 
                      create_table: bool = False) -> int:
        """
        从CSV文件导入数据到表
        
        Args:
            conn: 数据库连接对象
            table_name: 表名
            csv_path: CSV文件路径
            create_table: 是否自动创建表，默认为False
            
        Returns:
            导入的行数
            
        Raises:
            DatabaseException: 导入失败时抛出
            
        Examples:
            >>> handler = SQLiteHandler()
            >>> conn = handler.connect('example.db')
            >>> # 导入到现有表
            >>> rows = handler.import_from_csv(conn, 'users', 'users.csv')
            >>> # 自动创建表并导入
            >>> rows = handler.import_from_csv(conn, 'new_table', 'data.csv', create_table=True)
            >>> conn.commit()  # 提交事务
            >>> conn.close()
        """
        csv_path = Path(csv_path)
        
        # 检查CSV文件是否存在
        if not csv_path.exists():
            raise DatabaseException(f"CSV文件不存在: {csv_path}")
        
        try:
            import csv
            
            # 读取CSV文件
            with open(csv_path, 'r', newline='', encoding='utf-8') as csvfile:
                reader = csv.reader(csvfile)
                header = next(reader)  # 读取表头
                rows = list(reader)    # 读取数据行
            
            # 如果需要创建表
            if create_table:
                # 生成创建表的SQL语句
                columns = [f"\"{col}\" TEXT" for col in header]
                create_sql = f"CREATE TABLE IF NOT EXISTS {table_name} ({', '.join(columns)});"
                self.execute_script(conn, create_sql)
            
            # 生成插入数据的SQL语句
            placeholders = ', '.join(['?'] * len(header))
            insert_sql = f"INSERT INTO {table_name} ({', '.join([f'\"{col}\"' for col in header])}) VALUES ({placeholders})"
            
            # 插入数据
            cursor = conn.cursor()
            for row in rows:
                cursor.execute(insert_sql, row)
            
            # 获取插入的行数
            imported_rows = len(rows)
            
            cursor.close()
            
            logger.info(f"从CSV导入数据成功: {csv_path} -> {table_name} (导入 {imported_rows} 行)")
            return imported_rows
        except Exception as e:
            raise DatabaseException(f"从CSV导入数据失败: {e}")
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def backup_database(self, source_path: Union[str, Path], backup_path: Union[str, Path]) -> None:
        """
        备份SQLite数据库
        
        Args:
            source_path: 源数据库文件路径
            backup_path: 备份文件路径
            
        Raises:
            DatabaseException: 备份失败时抛出
            
        Examples:
            >>> handler = SQLiteHandler()
            >>> handler.backup_database('example.db', 'example_backup.db')
        """
        source_path = Path(source_path)
        backup_path = Path(backup_path)
        
        # 检查源数据库是否存在
        if not source_path.exists():
            raise DatabaseException(f"源数据库文件不存在: {source_path}")
        
        # 确保备份目录存在
        backup_path.parent.mkdir(parents=True, exist_ok=True)
        
        try:
            # 连接源数据库
            source_conn = self.sqlite3.connect(str(source_path))
            
            # 连接备份数据库
            backup_conn = self.sqlite3.connect(str(backup_path))
            
            # 执行备份
            source_conn.backup(backup_conn)
            
            # 关闭连接
            backup_conn.close()
            source_conn.close()
            
            logger.info(f"备份数据库成功: {source_path} -> {backup_path}")
        except Exception as e:
            raise DatabaseException(f"备份数据库失败: {e}")
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def optimize_database(self, db_path: Union[str, Path]) -> None:
        """
        优化SQLite数据库
        
        Args:
            db_path: 数据库文件路径
            
        Raises:
            DatabaseException: 优化失败时抛出
            
        Examples:
            >>> handler = SQLiteHandler()
            >>> handler.optimize_database('example.db')
        """
        try:
            # 连接数据库
            conn = self.connect(db_path)
            
            # 执行VACUUM操作
            conn.execute("VACUUM")
            
            # 执行ANALYZE操作
            conn.execute("ANALYZE")
            
            # 关闭连接
            conn.close()
            
            logger.info(f"优化数据库成功: {db_path}")
        except Exception as e:
            raise DatabaseException(f"优化数据库失败: {e}")


class AccessHandler:
    """
    Access数据库文件处理类
    
    提供对Microsoft Access数据库文件的读取、写入、查询等功能
    
    注意：此类需要安装pyodbc库
    pip install pyodbc
    """
    
    def __init__(self):
        """
        初始化Access处理器
        """
        try:
            import pyodbc
            self.pyodbc = pyodbc
        except ImportError as e:
            logger.error(f"初始化Access处理器失败: {e}")
            logger.error("请安装必要的依赖: pip install pyodbc")
            raise ImportError("请安装必要的依赖: pip install pyodbc") from e
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def connect(self, db_path: Union[str, Path]) -> 'pyodbc.Connection':
        """
        连接到Access数据库
        
        Args:
            db_path: 数据库文件路径
            
        Returns:
            数据库连接对象
            
        Raises:
            DatabaseException: 连接失败时抛出
            
        Examples:
            >>> handler = AccessHandler()
            >>> conn = handler.connect('example.accdb')
            >>> # 使用完毕后关闭连接
            >>> conn.close()
        """
        db_path = Path(db_path)
        
        # 检查数据库文件是否存在
        if not db_path.exists():
            raise DatabaseException(f"Access数据库文件不存在: {db_path}")
        
        try:
            # 构建连接字符串
            conn_str = f"Driver={{Microsoft Access Driver (*.mdb, *.accdb)}};DBQ={db_path};"
            
            # 连接到数据库
            conn = self.pyodbc.connect(conn_str)
            
            logger.info(f"连接到Access数据库成功: {db_path}")
            return conn
        except Exception as e:
            raise DatabaseException(f"连接到Access数据库失败: {e}")
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def execute_query(self, conn: 'pyodbc.Connection', query: str, params: Optional[Tuple] = None) -> List[Dict[str, Any]]:
        """
        执行查询语句
        
        Args:
            conn: 数据库连接对象
            query: SQL查询语句
            params: 查询参数，默认为None
            
        Returns:
            查询结果列表，每个元素是一个字典
            
        Raises:
            DatabaseException: 查询失败时抛出
            
        Examples:
            >>> handler = AccessHandler()
            >>> conn = handler.connect('example.accdb')
            >>> # 执行简单查询
            >>> results = handler.execute_query(conn, "SELECT * FROM Users")
            >>> # 执行带参数的查询
            >>> results = handler.execute_query(conn, "SELECT * FROM Users WHERE Age > ?", (18,))
            >>> conn.close()
        """
        try:
            cursor = conn.cursor()
            
            # 执行查询
            if params:
                cursor.execute(query, params)
            else:
                cursor.execute(query)
            
            # 获取列名
            columns = [column[0] for column in cursor.description]
            
            # 获取结果
            results = []
            for row in cursor.fetchall():
                results.append({columns[i]: value for i, value in enumerate(row)})
            
            cursor.close()
            
            logger.info(f"执行查询成功: {query[:50]}{'...' if len(query) > 50 else ''}")
            return results
        except Exception as e:
            raise DatabaseException(f"执行查询失败: {e}")
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def execute_update(self, conn: 'pyodbc.Connection', query: str, params: Optional[Tuple] = None) -> int:
        """
        执行更新语句（INSERT, UPDATE, DELETE等）
        
        Args:
            conn: 数据库连接对象
            query: SQL更新语句
            params: 更新参数，默认为None
            
        Returns:
            受影响的行数
            
        Raises:
            DatabaseException: 更新失败时抛出
            
        Examples:
            >>> handler = AccessHandler()
            >>> conn = handler.connect('example.accdb')
            >>> # 插入数据
            >>> affected = handler.execute_update(conn, "INSERT INTO Users (Name, Age) VALUES (?, ?)", ("张三", 25))
            >>> # 更新数据
            >>> affected = handler.execute_update(conn, "UPDATE Users SET Age = ? WHERE Name = ?", (26, "张三"))
            >>> # 删除数据
            >>> affected = handler.execute_update(conn, "DELETE FROM Users WHERE Name = ?", ("张三",))
            >>> conn.commit()  # 提交事务
            >>> conn.close()
        """
        try:
            cursor = conn.cursor()
            
            # 执行更新
            if params:
                cursor.execute(query, params)
            else:
                cursor.execute(query)
            
            # 获取受影响的行数
            affected_rows = cursor.rowcount
            
            cursor.close()
            
            logger.info(f"执行更新成功: {query[:50]}{'...' if len(query) > 50 else ''} (影响 {affected_rows} 行)")
            return affected_rows
        except Exception as e:
            raise DatabaseException(f"执行更新失败: {e}")
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def get_tables(self, conn: 'pyodbc.Connection') -> List[str]:
        """
        获取数据库中的所有表名
        
        Args:
            conn: 数据库连接对象
            
        Returns:
            表名列表
            
        Raises:
            DatabaseException: 获取失败时抛出
            
        Examples:
            >>> handler = AccessHandler()
            >>> conn = handler.connect('example.accdb')
            >>> tables = handler.get_tables(conn)
            >>> print(tables)
            >>> conn.close()
        """
        try:
            cursor = conn.cursor()
            
            # 查询所有表
            tables = []
            for row in cursor.tables(tableType='TABLE'):
                tables.append(row.table_name)
            
            cursor.close()
            
            logger.info(f"获取表名列表成功: {', '.join(tables)}")
            return tables
        except Exception as e:
            raise DatabaseException(f"获取表名列表失败: {e}")
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def get_table_schema(self, conn: 'pyodbc.Connection', table_name: str) -> List[Dict[str, Any]]:
        """
        获取表结构信息
        
        Args:
            conn: 数据库连接对象
            table_name: 表名
            
        Returns:
            表结构信息列表，每个元素是一个字段的信息字典
            
        Raises:
            DatabaseException: 获取失败时抛出
            
        Examples:
            >>> handler = AccessHandler()
            >>> conn = handler.connect('example.accdb')
            >>> schema = handler.get_table_schema(conn, 'Users')
            >>> for column in schema:
            ...     print(f"字段名: {column['name']}, 类型: {column['type_name']}")
            >>> conn.close()
        """
        try:
            cursor = conn.cursor()
            
            # 查询表结构
            columns = []
            for row in cursor.columns(table=table_name):
                columns.append({
                    'name': row.column_name,
                    'type_name': row.type_name,
                    'nullable': row.nullable,
                    'column_size': row.column_size
                })
            
            cursor.close()
            
            logger.info(f"获取表结构成功: {table_name}")
            return columns
        except Exception as e:
            raise DatabaseException(f"获取表结构失败: {e}")
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def export_to_csv(self, conn: 'pyodbc.Connection', table_name: str, csv_path: Union[str, Path]) -> None:
        """
        将表数据导出为CSV文件
        
        Args:
            conn: 数据库连接对象
            table_name: 表名
            csv_path: CSV文件路径
            
        Raises:
            DatabaseException: 导出失败时抛出
            
        Examples:
            >>> handler = AccessHandler()
            >>> conn = handler.connect('example.accdb')
            >>> handler.export_to_csv(conn, 'Users', 'users.csv')
            >>> conn.close()
        """
        csv_path = Path(csv_path)
        
        # 确保输出目录存在
        csv_path.parent.mkdir(parents=True, exist_ok=True)
        
        try:
            import csv
            
            # 获取表结构
            schema = self.get_table_schema(conn, table_name)
            column_names = [col['name'] for col in schema]
            
            # 查询所有数据
            cursor = conn.cursor()
            cursor.execute(f"SELECT * FROM [{table_name}]")
            rows = cursor.fetchall()
            
            # 写入CSV文件
            with open(csv_path, 'w', newline='', encoding='utf-8') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerow(column_names)  # 写入表头
                for row in rows:
                    writer.writerow(row)  # 写入数据行
            
            cursor.close()
            
            logger.info(f"导出表数据到CSV成功: {table_name} -> {csv_path}")
        except Exception as e:
            raise DatabaseException(f"导出表数据到CSV失败: {e}")
    
    @exception_handler(exception_type=Exception, reraise_as=DatabaseException)
    def import_from_csv(self, conn: 'pyodbc.Connection', table_name: str, csv_path: Union[str, Path]) -> int:
        """
        从CSV文件导入数据到表
        
        Args:
            conn: 数据库连接对象
            table_name: 表名
            csv_path: CSV文件路径
            
        Returns:
            导入的行数
            
        Raises:
            DatabaseException: 导入失败时抛出
            
        Examples:
            >>> handler = AccessHandler()
            >>> conn = handler.connect('example.accdb')
            >>> rows = handler.import_from_csv(conn, 'Users', 'users.csv')
            >>> conn.commit()  # 提交事务
            >>> conn.close()
        """
        csv_path = Path(csv_path)
        
        # 检查CSV文件是否存在
        if not csv_path.exists():
            raise DatabaseException(f"CSV文件不存在: {csv_path}")
        
        try:
            import csv
            
            # 读取CSV文件
            with open(csv_path, 'r', newline='', encoding='utf-8') as csvfile:
                reader = csv.reader(csvfile)
                header = next(reader)  # 读取表头
                rows = list(reader)    # 读取数据行
            
            # 获取表结构
            schema = self.get_table_schema(conn, table_name)
            table_columns = [col['name'] for col in schema]
            
            # 找出CSV中与表结构匹配的列
            matching_columns = []
            matching_indices = []
            
            for i, col in enumerate(header):
                if col in table_columns:
                    matching_columns.append(col)
                    matching_indices.append(i)
            
            if not matching_columns:
                raise DatabaseException(f"CSV文件中没有与表 {table_name} 匹配的列")
            
            # 生成插入数据的SQL语句
            placeholders = ', '.join(['?'] * len(matching_columns))
            insert_sql = f"INSERT INTO [{table_name}] ([{'], ['.join(matching_columns)}]) VALUES ({placeholders})"
            
            # 插入数据
            cursor = conn.cursor()
            imported_rows = 0
            
            for row in rows:
                # 提取匹配的列值
                values = [row[i] for i in matching_indices]
                cursor.execute(insert_sql, values)
                imported_rows += 1
            
            cursor.close()
            
            logger.info(f"从CSV导入数据成功: {csv_path} -> {table_name} (导入 {imported_rows} 行)")
            return imported_rows
        except Exception as e:
            raise DatabaseException(f"从CSV导入数据失败: {e}")